package com.wxy.care.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wxy.care.common.R;
import com.wxy.care.entity.Sensor;
import com.wxy.care.service.SensorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/sensor")
public class SensorController {
    @Autowired
    private SensorService sensorService;
    @GetMapping
    public R<String>catchMoment(String houseName,String slaveId,Integer place,String placeStr){
        if("".equals(houseName) || houseName == null || "".equals(slaveId) || slaveId == null || (("".equals(place) || place == null) && placeStr == null) )
        {
            return R.error("上传失败!");
        }
        Sensor sensor = new Sensor();
        sensor.setHouseName(houseName);
        if(place != null)
            sensor.setPlace(place);
        if(placeStr != null)
            sensor.setPlaceStr(placeStr);
        sensor.setSlaveId(slaveId);
        try {
            sensorService.save(sensor);
        }catch (DuplicateKeyException e){
            //System.out.println("重复ID!");
            return R.error("重复ID!");
        }
        return R.success("上传成功!");
    }
    @GetMapping("/all")
    public R<List<Sensor>>getAll(){
        return R.success(sensorService.list());
    }
    @DeleteMapping
    public R<String>deleteAll(){
        sensorService.remove(null);
        return R.success("已全部删除!");
    }
    @GetMapping("/ifsensor")
    public R<Boolean>ifSensor(String houseName){
        LambdaQueryWrapper<Sensor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Sensor::getHouseName,houseName).last("limit 1");
        Sensor sensor = sensorService.getOne(queryWrapper);
        return R.success(sensor != null);
    }
}
